package cn.spikego.advicelite.client.core.module

import cn.spikego.advicelite.client.core.event.impl.KeyPressEvent
import cn.spikego.advicelite.client.eventapi.EventManager
import cn.spikego.advicelite.client.eventapi.EventTarget
import cn.spikego.advicelite.common.LogUtil
import org.reflections.Reflections
import org.reflections.scanners.SubTypesScanner

class ModuleManager {

    private val moduleList: MutableList<Module> = ArrayList()

    @Throws(InstantiationException::class, IllegalAccessException::class)
    fun initialize() {
        val reflections = Reflections("cn.spikego.rtlite.client.core.module.impl", SubTypesScanner())
        val modules = reflections.getSubTypesOf(Module::class.java)

        for (module in modules) {
            val instance = module.getDeclaredConstructor().newInstance()
            LogUtil.log("Loaded module: %s", module.simpleName)
            moduleList.add(instance)
        }

        EventManager.register(this)
    }

    @EventTarget
    fun onKeyPress(event: KeyPressEvent) {
        if (event.pressType == 1) {
            moduleList.forEach { m ->
                val keybind = m.keybind
                if (keybind != 0 && keybind == event.keyCode) {
                    m.toggle()
                }
            }
        }
    }

    fun toggleModule(module: Module) {
        module.toggle()
    }

    fun getModuleList(): List<Module> = moduleList
}